package com.aiti.lulian.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.bo.CustomerFollowUpRecordBo;
import com.aiti.lulian.bo.ShangJiFollowUpRecordBo;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CommunicateInfoMapper;
import com.aiti.lulian.mapper.CustomerFollowUpRecordMapper;
import com.aiti.lulian.mapper.LuLianEnterpriseMapper;
import com.aiti.lulian.mapper.ShangJiFollowUpRecordMapper;
import com.aiti.lulian.service.ICustomerFollowUpRecordService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.service.IShangJiFollowUpRecordService;
import com.aiti.lulian.vo.CustomerFollowUpRecordVo;
import com.aiti.lulian.vo.ShangjiFollowUpRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ShangJiFollowUpRecordServiceImpl extends BaseSerivceImpl<ShangJiFollowUpRecordMapper, ShangjiFollowUpRecord> implements IShangJiFollowUpRecordService {

    private final ShangJiFollowUpRecordMapper baseMapper;

    /** 远程调用获取用户信息 */
    private final CloudShowManagerSubService cloudShowManagerSubService;

    /** 企业的查询信息 */
    private final LuLianEnterpriseMapper luLianEnterpriseMapper;

    /** 商机 */
    private final CommunicateInfoMapper communicateInfoMapper;

    @Autowired
    private ILuLianEnterpriseUserService luLianEnterpriseUserService;

    /**
     * 查询客户的跟进记录
     * @param bo 前端传入的参数
     * @return 跟进的记录
     */
    @Override
    public Map<String,Object> queryCustomerList(Page<CustomerFollowUpRecord> page, ShangJiFollowUpRecordBo bo) {
        Map<String,Object> returnResult=  new HashMap<>();

        List<ShangjiFollowUpRecordVo> shangJiFollowUpRecords = baseMapper.selectCustomPage(page,bo);
        List<ShangjiFollowUpRecordVo> list = new ArrayList<>();

        //获取到查询的数据中是客户信息的Id
        Map<String, Map<String, String>> userIdToRealNameMap = new HashMap<>();
        if(StringUtils.equals(bo.getRecordType(),"2")){
            List<String> userId = shangJiFollowUpRecords.stream()
                    .filter(item -> StringUtils.equals(item.getRecordType(), "2"))
                    .map(ShangjiFollowUpRecordVo::getBaseCreateBy)
                    .collect(Collectors.toList());
            Message usersInfo = cloudShowManagerSubService.getUsersInfo(userId);
            if(Objects.equals(usersInfo.getCode(), MessageCodeConstant.MSG_FAIL_CODE)){
                throw new RuntimeException("获取用户信息失败");
            }
            userIdToRealNameMap = (Map<String, Map<String, String>>)usersInfo.getObj();
        }

        for(ShangjiFollowUpRecordVo temp : shangJiFollowUpRecords){
            ShangjiFollowUpRecordVo tempVo = ShangjiFollowUpRecordVo.builder()
                    .baseId(temp.getBaseId())
                    .content(temp.getContent())
                    .baseCreateTime(temp.getBaseCreateTime())
                    .shangJiName(temp.getShangJiName())
                    .build();

            //设置用户名称
            if(StringUtils.equals(temp.getRecordType(),"2")){
                Map<String, String> stringStringMap = userIdToRealNameMap.get(temp.getBaseCreateBy());
                if(stringStringMap != null){
                    tempVo.setCustomerName(stringStringMap.get("realname"));
                }
            }

            list.add(tempVo);
        }
        returnResult.put("rows",list);
        return returnResult;
    }

    /**
     * 新增跟进记录
     *
     * @param bo 参数
     */
    @Override
    public boolean addFollowUpRecord(ShangJiFollowUpRecordBo bo) {
        ShangjiFollowUpRecord record = new ShangjiFollowUpRecord();
        BeanUtils.copyProperties(bo,record);
        if(record.getFollowUpTime() == null){
            //如果跟进时间是空的，则现在的时候就是跟进时间
            record.setFollowUpTime(DateUtil.date());
        }
        record.setBaseCreateTime(DateUtil.date());
        record.setBaseUpdateTime(DateUtil.date());
        int rows = baseMapper.insert(record);
        return rows > 0;
    }

    /**
     * 查询某个记录的详情
     *
     * @param bo 参数
     * @return 结果
     */
    @Override
    public ShangjiFollowUpRecordVo queryCustomerFollowUpRecordDetail(ShangJiFollowUpRecordBo bo) {
        LambdaQueryWrapper<ShangjiFollowUpRecord> lqw = buildQueryWrapper(bo);
        ShangjiFollowUpRecord customerFollowUpRecord = baseMapper.selectOne(lqw);
        ShangjiFollowUpRecordVo vo = new ShangjiFollowUpRecordVo();
        if(customerFollowUpRecord != null){
            BeanUtils.copyProperties(customerFollowUpRecord,vo);
            //远程调用获取客户名称
            if(StringUtils.equals(vo.getRecordType(),"2")){
                CommunicateInfo communicateInfo = communicateInfoMapper.selectById(customerFollowUpRecord.getCustomerId());
                if(communicateInfo != null){
                    vo.setCustomerName(communicateInfo.getProductName());
                }
            }

            //获取到查询的数据中是客户信息的Id
            Message usersInfo = cloudShowManagerSubService.getUserInfo(customerFollowUpRecord.getBaseCreateBy());
            if (usersInfo == null) {
                throw new RuntimeException("获取用户信息失败");
            }
            Object obj = usersInfo.getObj();
            if (obj == null) {
                throw new RuntimeException("查询用户为空");
            }

            if(Objects.equals(usersInfo.getCode(), MessageCodeConstant.MSG_FAIL_CODE)){
                throw new RuntimeException("获取用户信息失败");
            }

            ObjectMapper mapper = new ObjectMapper();
            Map resultMap = mapper.convertValue(obj, Map.class);
            String realname = (String)resultMap.get("realname");
            vo.setBaseCreateByName(realname);
        }
        return vo;
    }

    /**
     * 更新根进记录
     *
     * @param bo 参数
     * @return 结果
     */
    @Override
    public boolean editCustomerFollowUpRecord(ShangJiFollowUpRecordBo bo) {
        LambdaUpdateWrapper<ShangjiFollowUpRecord> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(ShangjiFollowUpRecord::getBaseId,bo.getBaseId());
        lqw.eq(ShangjiFollowUpRecord::getRecordType,bo.getRecordType());
        lqw.eq(ShangjiFollowUpRecord::getCustomerId,bo.getCustomerId());

        lqw.set(ShangjiFollowUpRecord::getLinkMan,bo.getLinkMan());
        lqw.set(ShangjiFollowUpRecord::getFollowUpTime,bo.getFollowUpTime());
        lqw.set(ShangjiFollowUpRecord::getFollowUpType,bo.getFollowUpType());
        lqw.set(ShangjiFollowUpRecord::getContent,bo.getContent());
        lqw.set(ShangjiFollowUpRecord::getBaseUpdateTime,LocalDateTime.now());

        int rows = baseMapper.update(null, lqw);
        return rows > 0;
    }

    @Override
    public boolean deleteShangJiFollowUpRecord(ShangJiFollowUpRecordBo bo) {
        int rows = baseMapper.deleteById(bo.getBaseId());
        return rows > 0;
    }

    @Override
    public Message followUpPage(Page<ShangjiFollowUpRecord> page, ShangJiFollowUpRecordBo bo) {
        Map<String,Object> returnResult=  new HashMap<>();
        String userId = bo.getUserId();
        Message userRoleMessage = cloudShowManagerSubService.getRoleByUserId(userId);
        if (userRoleMessage == null) {
            return Message.fail("获取角色信息失败！");
        }
        String roleIds = (String)userRoleMessage.getObj();
        if(userRoleMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
            throw new RuntimeException("查询角色失败");
        }
        if(!StringUtils.isEmpty(roleIds)){
            String[] split = roleIds.split(StrUtil.COMMA);
            boolean systemAdmin = Arrays.stream(split).filter(f->"1".equals(f)).count() > 0;
            bo.setSystemAdmin(systemAdmin);
            if(!systemAdmin){
                boolean isEnterpriseAdmin = Arrays.stream(split).filter(f->StringUtils.containsAny(f, "043ea2e3e02c4aa591df1f83e65069bc", "8836c75af939406a9f41128826f6d8b3")).count() > 0;
                bo.setEnterpriseAdmin(isEnterpriseAdmin);
                if(!isEnterpriseAdmin){
                    Message message = cloudShowManagerSubService.getUserInfo(userId);
                    if (message == null) {
                        return Message.fail("获取用户信息失败！");
                    }
                    Object obj = message.getObj();
                    if (obj == null) {
                        return Message.fail("获取用户信息失败！");
                    }
                    if (message.getCode() == 1) {
                        return Message.fail("查询用户信息错误");
                    }
                    ObjectMapper mapper = new ObjectMapper();
                    Map resultMap = mapper.convertValue(obj, Map.class);
                    String deptPermission = (String)resultMap.get("deptPermission");
                    String deptId = (String)resultMap.get("deptId");
                    bo.setDeptPermission(deptPermission);
                    bo.setDeptId(deptId);
                    List<String> deptList = new ArrayList(){{add(deptId);}};
                    Message deptMessage = cloudShowManagerSubService.getSubDeptByDeptId(deptId);
                    if(deptMessage==null || deptMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                        throw new RuntimeException("查询子级部门失败");
                    }
                    String deptObj = (String)deptMessage.getObj();
                    if(StringUtils.isNotBlank(deptObj)){
                        String[] deptSplit = deptObj.split(StrUtil.COMMA);
                        for(String temp : deptSplit){
                            deptList.add(temp);
                        }
                    }
                    bo.setDeptList(deptList);
                }else{
                    LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
                    if(enterpriseUser != null){
                        String enterpriseId = enterpriseUser.getEnterpriseId();
                        bo.setEnterpriseId(enterpriseId);
                    }
                }
            }
        }


        List<ShangjiFollowUpRecordVo> shangJiFollowUpRecords = baseMapper.followUpPage(page,bo);
        returnResult.put("rows",shangJiFollowUpRecords);
        returnResult.put("total", page.getTotal());
        return Message.success(returnResult);
    }

    /**
     * 构建基础的查询规则
     * @param bo 参数
     * @return 查询规则
     */
    private LambdaQueryWrapper<ShangjiFollowUpRecord> buildQueryWrapper(ShangJiFollowUpRecordBo bo) {
        LambdaQueryWrapper<ShangjiFollowUpRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getBaseId()),ShangjiFollowUpRecord::getBaseId,bo.getBaseId());
        lqw.eq(StringUtils.isNotBlank(bo.getCustomerId()), ShangjiFollowUpRecord::getCustomerId, bo.getCustomerId());
        lqw.eq(StringUtils.isNotBlank(bo.getFollowUpType()), ShangjiFollowUpRecord::getFollowUpType, bo.getFollowUpType());
        lqw.orderByDesc(ShangjiFollowUpRecord::getFollowUpTime);
        return lqw;
    }
}
